#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import urllib2
import base64
import  socket
import fcntl
import struct
username = 'admin'
password = '123456'
dns1 = '192.168.2.11'
zone = 'cango.local'
adapter = "eno16777736"

system_name = socket.gethostname()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip = socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', adapter[:15])
    )[20:24])

params = {
    "dns_server": dns1,
    "zone_name": zone,
    "record_name": system_name,
    "record_data": ip,
}


url = "http://127.0.0.1:88/api/bindapi/"
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent,
            'Content-Type': "application/json"
          }

def dns_reg():
    req = urllib2.Request(url=url,headers=headers,data=json.dumps(params))
    base64string = base64.b64encode('%s:%s' % (username, password))
    req.add_header("Authorization", "Basic %s" % base64string)
    response = urllib2.urlopen(req)
    return response

def dns_query():
    dns_path = url + system_name + '/'
    req = urllib2.Request(url=dns_path, headers=headers)
    base64string = base64.b64encode('%s:%s' % (username, password))
    req.add_header("Authorization", "Basic %s" % base64string)
    try:
        urllib2.urlopen(req)
    except urllib2.URLError, e:
        return e.reason

def dns_update():
    dns_path = url + system_name + '/'
    req = urllib2.Request(url=dns_path, headers=headers, data=json.dumps(params))
    base64string = base64.b64encode('%s:%s' % (username, password))
    req.add_header("Authorization", "Basic %s" % base64string)
    req.get_method = lambda: 'PUT'
    try:
        response = urllib2.urlopen(req)
    except urllib2.URLError, e:
        return e.reason

if __name__ == "__main__":
     if dns_query() == "Not Found":
        dns_reg()
     else:
         dns_update()